/*
 *  Copyright 2010 Massimiliano Mazzarolo
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0
 *        
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package grails.coherence.extractor;

import static com.tangosol.util.ExternalizableHelper.readSafeUTF;
import static com.tangosol.util.ExternalizableHelper.writeSafeUTF;
import groovy.lang.GroovyObject;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import com.tangosol.io.ExternalizableLite;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
import com.tangosol.util.ValueExtractor;


/**
 * Extract values from cached {@link GroovyObject} using the usual groovy property syntax.
 * 
 * @author Massimiliano Mazzarolo
 * 
 * @since 0.1
 *
 */
public class GroovyPropertyValueExtractor implements
		ValueExtractor, PortableObject, ExternalizableLite {


	/**
	 * 
	 */
	private static final long serialVersionUID = 3486442117485257103L;

	private String propertyName;

	public GroovyPropertyValueExtractor() {	
	}
	
	public GroovyPropertyValueExtractor(String propertyName) {
		this.propertyName = propertyName;
	}

	@Override
	public Object extract(Object value) {
		if (value instanceof GroovyObject) {
			return ((GroovyObject)value).getProperty(propertyName);
		}
		return null;
	}

	@Override
	public void readExternal(PofReader reader) throws IOException {
		this.propertyName = reader.readString(1);
	}

	@Override
	public void writeExternal(PofWriter writer) throws IOException {
		writer.writeString(1, this.propertyName);
	}

	@Override
	public void readExternal(DataInput in) throws IOException {
		this.propertyName = readSafeUTF(in);
	}

	@Override
	public void writeExternal(DataOutput out) throws IOException {
		writeSafeUTF(out, propertyName);
	}

	public String getGroovyPropertyExtracted() {
		return propertyName;
	}
}
